﻿using System;
using SpLocalizer.Common.Extensions;

namespace Core.Threading.Locks
{
    public sealed class Isolated<T>
    {
        private readonly object _locker;
        private readonly T _value;

        public Isolated(T value)
            : this(value, new object())
        {
            _value = value;
        }

        public Isolated(T value, object locker)
        {
            if (locker.IsNull())
                throw new ArgumentNullException("locker", "locker is null");
            _value = value;
            _locker = locker;
        }

        public TResult Lock<TResult>(Func<T, TResult> action)
        {
            lock (_locker)
            {
                return action(_value);
            }
        }

        public void Lock(Action<T> action)
        {
            lock (_locker)
            {
                action(_value);
            }
        }
    }
}